#!/usr/bin/env python
# coding=utf-8-sgi
# __author__ = 'Yunchao Ling'

import csv
import re
import os
import fire
import shutil

allow_fenqu = set(
    ["呼吸系统", "生化研究方法", "海洋与淡水生物学", "临床神经病学", "皮肤病学", "环境科学与生态学", "泌尿学与肾脏学", "医学", "发育生物学", "高分子科学", "心脏和心血管系统",
     "免疫学", "医学：伦理", "生化与分子生物学", "数学与计算生物学", "生物工程与应用微生物", "农业工程", "急救医学", "传染病学", "卫生保健与服务", "水资源", "真菌学", "医学：法",
     "肿瘤学", "行为科学", "病毒学", "护理", "药学", "寄生虫学", "妇产科学", "风湿病学", "药物化学", "康复医学", "神经科学", "外科", "工程：生物医学", "解剖学与形态学",
     "外周血管病", "初级卫生保健", "病理学", "耳鼻喉科学", "细胞与组织工程", "生物物理", "核医学", "神经成像", "医学实验技术", "老年医学", "心理学", "骨科", "医学：信息",
     "毒理学", "移植", "过敏", "眼科学", "生殖生物学", "生物", "生理学", "男科学", "牙科与口腔外科", "胃肠肝病学", "全科医学与补充医学", "精神病学", "生物学", "麻醉学",
     "动物学", "兽医学", "内分泌学与代谢", "儿科", "食品科技", "公共卫生、环境卫生与职业卫生", "生态学", "进化生物学", "危重病医学", "遗传学", "综合性期刊", "药物滥用",
     "微生物学", "环境科学", "血液学", "物理化学", "医学：内科", "热带医学", "工程：环境", "医学：研究与实验", "营养学", "细胞生物学", "计算机：人工智能"])


def get_paper_info(filepath: str):
    result = {}
    with open(filepath, 'r', encoding='utf-8-sig') as f:
        f_csv = csv.reader(f)
        headers = next(f_csv)
        for row in f_csv:
            line = dict(zip(headers, row))
            # print(format_journal(line["journal_title"], line["year"], line["volume"], line["issue"], line["page"]))
            # print("%s\t%s" % (line["journal_zky_section"], get_fenqu(line["journal_zky_section"])))
            # print("%s\t%s\t%s" % (line["pmid"],line["impact_factor"],get_fenqu(line["journal_zky_section"])))
            result[str(line["pmid"].strip())] = [line["impact_factor"], get_fenqu(line["journal_zky_section"])]
    return result


def format_journal(journal_title: str, year: str, volume: str, issue: str, page: str):
    result = ""
    if journal_title != "":
        result += journal_title.strip() + "."
        if year != "":
            result += " " + year
            if volume != "":
                result += ", " + volume
                if issue != "":
                    result += "(" + issue + ")"
                    if page != "":
                        result += ":" + page
    result += "."
    return result


def get_fenqu(fenqu_list: str):
    if fenqu_list.strip() == "":
        return ""
    else:
        min_fenqu = 5
        splitfenqu = fenqu_list.split("; ")
        for fenqu in splitfenqu:
            match = re.search("^(.*?)(\d+)", fenqu)
            if match is not None:
                if match.group(1) in allow_fenqu:
                    min_fenqu = min(int(match.group(2)), min_fenqu)
        return str(min_fenqu) + "区"


# 从pmid_doid.txt文件中获取每篇文献对应的多个doid，返回字典
def get_disease_doid(filepath):
    result = {}
    current_doid = []
    current_pmid = ""
    infile = open(filepath, "r")
    current_pmid = infile.readline().strip()[1:]
    for line in infile:
        line = line.rstrip()
        if line.startswith(">"):
            result[current_pmid] = current_doid
            current_pmid = line[1:]
            current_doid = []
        else:
            if line != "":
                current_doid.append(line)
    if len(current_doid) > 0:
        result[current_pmid] = current_doid
    infile.close()
    return result


def get_disease_paper_count():
    # outfile=open("/Users/genesis/Seafile/Work/微生物知识库/pmid_sec2.txt","w")
    disease_paper_count = {}
    paper_info = get_paper_info("/Users/genesis/Seafile/Work/微生物知识库/result3.csv")
    paper_doid = get_disease_doid("/Users/genesis/Seafile/Work/微生物知识库/pmid_doid.txt")
    for key in paper_doid:
        impact_fenqu = paper_info[key]
        unique = len(paper_doid[key])
        for doid in paper_doid[key]:
            if doid not in disease_paper_count:
                disease_paper_count[doid] = {"total": 0, "if10": 0, "if5": 0, "sci": 0, "section1": 0, "section2": 0,
                                             "uni_total": 0, "uni_if10": 0, "uni_if5": 0, "uni_sci": 0,
                                             "uni_section1": 0, "uni_section2": 0}
            disease_paper_count[doid]["total"] += 1
            if unique == 1:
                disease_paper_count[doid]["uni_total"] += 1
            if impact_fenqu[0] != "":
                impact_factor = float(impact_fenqu[0])
                disease_paper_count[doid]["sci"] += 1
                if unique == 1:
                    disease_paper_count[doid]["uni_sci"] += 1
                if impact_factor >= 10:
                    disease_paper_count[doid]["if10"] += 1
                    if unique == 1:
                        disease_paper_count[doid]["uni_if10"] += 1
                if impact_factor >= 5:
                    disease_paper_count[doid]["if5"] += 1
                    if unique == 1:
                        disease_paper_count[doid]["uni_if5"] += 1
            if impact_fenqu[1] != "":
                if impact_fenqu[1] == "1区":
                    disease_paper_count[doid]["section1"] += 1
                    disease_paper_count[doid]["section2"] += 1
                    if unique == 1:
                        disease_paper_count[doid]["uni_section1"] += 1
                        disease_paper_count[doid]["uni_section2"] += 1
                        # outfile.write(key+"\n")
                        # outfile.flush()
                elif impact_fenqu[1] == "2区":
                    disease_paper_count[doid]["section2"] += 1
                    if unique == 1:
                        disease_paper_count[doid]["uni_section2"] += 1
                        # outfile.write(key + "\n")
                        # outfile.flush()
    # outfile.close()
    return disease_paper_count


def integrate_disease_paper_count():
    disease_paper_count = get_disease_paper_count()
    infile = open("/Users/genesis/Seafile/Work/微生物知识库/disease_list.txt", "r")
    outfile = open("/Users/genesis/Seafile/Work/微生物知识库/disease_list_count.txt", "w")
    outfile.write(infile.readline().rstrip(
        "\n") + "\ttotal\tsci\tif>=5\tif>=10\t2区以上\t1区\tunique_total\tunique_sci\tunique_if>=5\tunique_if>=10\tunique_2区以上\tunique_1区\n")
    outfile.flush()
    for line in infile:
        line = line.rstrip("\n")
        doid = line.split("\t")[2].strip()
        if doid not in disease_paper_count:
            outfile.write(line + "\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\n")
            outfile.flush()
        else:
            counts = disease_paper_count[doid]
            outfile.write(line + "\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (
                counts["total"], counts["sci"], counts["if5"], counts["if10"], counts["section2"], counts["section1"],
                counts["uni_total"], counts["uni_sci"], counts["uni_if5"], counts["uni_if10"], counts["uni_section2"],
                counts["uni_section1"]))
            outfile.flush()
    outfile.close()
    infile.close()


def distribute_pdf_to_doid(pmid_doid_filepath: str, pdf_filepath):
    doid_download_pdf = {}
    paper_doid = get_disease_doid(pmid_doid_filepath)
    print(paper_doid)
    for filename in os.listdir(pdf_filepath):
        if os.path.isfile(os.path.join(pdf_filepath, filename)):
            name = filename.split(".")[0]
            if name in paper_doid:
                for doid in paper_doid[name]:
                    if doid in doid_download_pdf:
                        doid_download_pdf[doid] += 1
                    else:
                        doid_download_pdf[doid] = 1
                doid_dir = doid.replace(":", "-")
                if not os.path.exists(os.path.join(pdf_filepath, doid_dir)):
                    os.mkdir(os.path.join(pdf_filepath, doid_dir))
                shutil.copy(os.path.join(pdf_filepath, filename), os.path.join(pdf_filepath, doid_dir))

    # infile = open("D:/Seafile/Work/微生物知识库/disease_list.txt", "r")
    # for line in infile:
    #     line = line.rstrip("\n")
    #     doid = line.split("\t")[2].strip()
    #     if doid in doid_download_pdf:
    #         print(doid_download_pdf[doid])
    #     else:
    #         print("0")
    # infile.close()


if __name__ == "__main__":
    # integrate_disease_paper_count()
    # get_disease_paper_count()
    fire.Fire()
